package com.beta.service.impl;

import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.beta.entity.CRegionLevels;
import com.beta.mapper.CRegionLevelsMapper;
import com.beta.service.ICRegionLevelsService;
import com.beta.dto.region.CRegionDto;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 *
 * CRegionLevels 表数据服务层接口实现类
 *
 */
@Service("cRegionLevelsService")
public class CRegionLevelsService extends SuperServiceImpl<CRegionLevelsMapper, CRegionLevels> implements ICRegionLevelsService {

    @Override
    public List<CRegionDto> getTopThreeLevelRegions() {
        List<CRegionDto> topThreeLevelRegions = baseMapper.selectRegionsOfLevels(Arrays.asList(1, 2, 3));
        return groupingByRegions(topThreeLevelRegions);
    }

    private List<CRegionDto> groupingByRegions(List<CRegionDto> regions) {
        if (CollectionUtils.isEmpty(regions)) {
            return Collections.emptyList();
        }

        List<CRegionDto> result = new ArrayList<>();
        Map<Integer, CRegionDto> regionIdMap = regions.stream().collect(Collectors.toMap(CRegionDto::getCode, Function.identity()));

        regions.forEach(region -> {
            CRegionDto parentRegion = regionIdMap.get(region.getParentId());
            if (Objects.isNull(parentRegion)) {
                result.add(region);
            } else {
                List<CRegionDto> subRegions = parentRegion.getSubRegions();
                if (Objects.isNull(subRegions)) {
                    subRegions = new ArrayList<>();
                    parentRegion.setSubRegions(subRegions);
                }
                subRegions.add(region);
            }
        });
        return result;
    }

    @Override
    public List<CRegionDto> getRegionsByParentId(Integer parentId) {
        if (Objects.isNull(parentId)) {
            return Collections.emptyList();
        }

        return baseMapper.selectRegionsByParentId(parentId);
    }

}